/*
  Copyright 2007 Anders Båtstrand

      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.

 */

package org.dyndns.anderlin.jmplayer.client.ui.wizard;

import org.dyndns.anderlin.jmplayer.client.utilities.FileParser;
import org.dyndns.anderlin.jmplayer.client.ui.AlbumForm;
import org.dyndns.anderlin.jmplayer.client.ui.TrackForm;
import org.dyndns.anderlin.jmplayer.model.Album;
import org.dyndns.anderlin.jmplayer.model.Track;
import org.dyndns.anderlin.jmplayer.service.GenericService;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.richclient.application.event.LifecycleApplicationEvent;
import org.springframework.richclient.command.ActionCommandExecutor;
import org.springframework.richclient.dialog.MessageDialog;
import org.springframework.richclient.form.CompoundForm;
import org.springframework.richclient.form.FormModelHelper;
import org.springframework.richclient.wizard.AbstractWizard;
import org.springframework.richclient.wizard.FormBackedWizardPage;
import org.springframework.richclient.wizard.WizardDialog;
import org.springframework.util.Assert;

import javax.swing.*;
import java.io.File;
import java.util.HashSet;
import java.util.Set;

public class NewAlbumWizard extends AbstractWizard implements ActionCommandExecutor, InitializingBean {

    private WizardDialog wizardDialog;

    private CompoundForm wizardForm;

    private Set<CompoundForm> wizardForms = new HashSet<CompoundForm>();

    private File[] files;

    private GenericService<Album> albumService;

    private GenericService<Track> trackService;

    public NewAlbumWizard() {
        super("newAlbumWizard");
    }


    public void setAlbumService(GenericService<Album> albumService) {
        this.albumService = albumService;
    }


    public void setTrackService(GenericService<Track> trackService) {
        this.trackService = trackService;
    }

    public void afterPropertiesSet() throws Exception {
        Assert.notNull(albumService, "A albumService must be provided.");
        Assert.notNull(trackService, "A trackService must be provided.");
    }

    public void addPages() {
        addPage(new FormBackedWizardPage(new AlbumForm(FormModelHelper.createChildPageFormModel(wizardForm.getFormModel()))));
        for (CompoundForm wizardFormTmp : wizardForms) {
            addPage(new FormBackedWizardPage(new TrackForm(FormModelHelper.createChildPageFormModel(wizardFormTmp.getFormModel()))));
        }
    }

    public void execute() {

        // TODO: gettext...
        MessageDialog dialog = new MessageDialog("New album", "Please select the files belonging to this album");
        dialog.showDialog();

        // Get files from the user
        JFileChooser fc = new JFileChooser();
        fc.setMultiSelectionEnabled(true);
        int returnVal = fc.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            files = fc.getSelectedFiles();
        }

        // no files selected, or cancel pressed
        if (files == null || files.length == 0) {
            return;
        }

        // add album form
        if (wizardDialog == null) {
            wizardDialog = new WizardDialog(this);
        }
        wizardForm = new CompoundForm();
        Album album = FileParser.getAlbum(files[0]);
        wizardForm.setFormObject(album);

        // add track forms
        for (File file : files) {
            CompoundForm wizardFormTmp = new CompoundForm();
            Track track = FileParser.getTrack(file);
            track.setAlbum(album);
            wizardFormTmp.setFormObject(track);
            wizardForms.add(wizardFormTmp);
        }

        wizardDialog.showDialog();
    }

    //public WizardPage getNextPage(WizardPage page) {
    // if this was the generic track, add information to all others

    //   return super.getNextPage(page);
    //}

    protected boolean onFinish() {
        // save album
        Album newAlbum = getNewAlbum();
        newAlbum = albumService.saveOrUpdate(newAlbum);
        getApplicationContext()
                .publishEvent(new LifecycleApplicationEvent(LifecycleApplicationEvent.CREATED, newAlbum));

        for (CompoundForm wizardForm : wizardForms) {
            Track newTrack = getNewTrack(wizardForm);
            // update the album
            newTrack.setAlbum(newAlbum);
            newTrack.getAlbum().getTracks().add(newTrack);
            System.out.println("About to save: " + newTrack);
            System.out.println("Piece: " + newTrack.getPiece());
            newTrack = trackService.saveOrUpdate(newTrack);
            getApplicationContext()
                    .publishEvent(new LifecycleApplicationEvent(LifecycleApplicationEvent.CREATED, newTrack));
        }
        return true;
    }

    private Track getNewTrack(CompoundForm wizardForm) {
        wizardForm.commit();
        return (Track) wizardForm.getFormObject();
    }

    private Album getNewAlbum() {
        wizardForm.commit();
        return (Album) wizardForm.getFormObject();
    }

}